package com.hulman.oms.service;

import com.hulman.oms.bean.MsgSummary;
import com.hulman.oms.bean.Result;
import com.hulman.oms.bean.Msg;
import com.hulman.oms.dao.MsgDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: maxwellens
 */
@Service
public class MsgService
{
    @Autowired
    private MsgDao msgDao;
    @Autowired
    private MiniProgramService miniProgramService;

    public List<Msg> findMsgs(Map<String, Object> map)
    {
        return msgDao.findMsgs(map);
    }

    public Integer findMsgsCount(Map<String, Object> map)
    {
        return msgDao.findMsgsCount(map);
    }

    public List<Msg> findLatestMsgs(Integer ownerId, Integer msgId)
    {
        return msgDao.findLatestMsgs(ownerId, msgId);
    }

    public Msg findLatestMsg(Integer ownerId, String type)
    {
        return msgDao.findLatestMsg(ownerId, type);
    }

    public MsgSummary findMsgSummary(Integer ownerId, String type)
    {
        MsgSummary msgSummary = new MsgSummary();
        Map<String, Object> map = new HashMap<>();
        map.put("type", type);
        map.put("ownerId", ownerId);
        map.put("state", 0);
        Integer count = findMsgsCount(map);
        msgSummary.setCount(count);
        Msg msg = findLatestMsg(ownerId, type);
        if (msg != null)
        {
            msgSummary.setNote(msg.getTitle());
            msgSummary.setTime(msg.getSimpleCreateTime());
        }
        return msgSummary;
    }

    public Result findMsgsResult(Map<String, Object> map)
    {
        Integer page = (Integer) map.get("page");
        Integer limit = (Integer) map.get("limit");
        if (page != null && limit != null)
        {
            map.put("start", (page - 1) * limit);
            map.put("length", limit);
        }
        int count = msgDao.findMsgsCount(map);
        List<Msg> data = msgDao.findMsgs(map);
        return new Result(data, count);
    }

    public Msg findMsgById(Integer id)
    {
        return msgDao.findMsgById(id);
    }

    public void sendMsg(Msg msg)
    {
        //发送系统消息
        msg.setState(Msg.STATE_UNREAD);
        msg.setCreateTime(new Date());
        msgDao.insertMsg(msg);
        //异步发送企业微信消息
        miniProgramService.sendMsgAsync(msg);
    }

    public void readMsg(Integer id)
    {
        msgDao.readMsg(id);
    }

    public void deleteMsgById(Integer id)
    {
        msgDao.deleteMsgById(id);
    }

    public void readAllMsgs(Integer ownerId, String type)
    {
        msgDao.readAllMsgs(ownerId, type);
    }

    public void clearAllMsgs(Integer ownerId, String type)
    {
        msgDao.clearAllMsgs(ownerId, type);
    }

    public void deleteMsgs(int[] ids)
    {
        msgDao.deleteMsgs(ids);
    }

}
